package api

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"one_exam/global"
	"one_exam/internal/model/dao"
	"one_exam/internal/model/service"
)

type GoodsForm struct {
	Name     string `form:"name" binding:"required" json:"name"`
	PriceId  int    `form:"priceId" binding:"required" json:"priceId"`
	SizeData int    `form:"sizeDate" binding:"required" json:"sizeData"`
	Buy      int    `form:"buy" binding:"required" json:"buy"`
	Old      int    `form:"old" binding:"required" json:"old"`
}

func AddGoods(c *gin.Context) {
	var form GoodsForm
	err := c.ShouldBind(&form)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"message": "参数获取失败", "error": err.Error()})
		return
	}
	var price dao.Price
	price, b := service.FindPriceId(form.PriceId)
	if !b {
		c.JSON(http.StatusInternalServerError, gin.H{"message": "价格区间不存在"})
		return
	}
	goods := dao.Goods{
		Name:    form.Name,
		Size:    form.SizeData,
		PriceId: form.PriceId,
		Price:   price.Price,
		Buy:     form.Buy,
		Old:     form.Old,
	}
	tx := global.DB.Begin() //开启事务
	err = global.DB.Create(&goods).Error
	if err != nil {
		tx.Rollback()
		c.JSON(http.StatusInternalServerError, gin.H{"message": "发布失败", "error": err.Error()})
		return
	}
	tx.Commit() //提交事务
	c.JSON(http.StatusOK, gin.H{"message": "发布成功", "goods": goods})
}

type GoodsListForm struct {
	Name     string `form:"name" binding:"required" json:"name"`
	SizeData int    `form:"sizeDate" json:"sizeData"`
	Old      int    `form:"old" json:"old"`
}

func GoodsList(c *gin.Context) {
	var form GoodsListForm
	err := c.ShouldBind(&form)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"message": "参数获取失败"})
		return
	}
	list, err := service.List(form.Name, form.SizeData, form.Old)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"message": "列表展示失败"})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": "200",
		"list": list,
	})
}

type WouldForm struct {
	GoodsId int     `form:"goodsId" binding:"required" json:"goodsId"`
	Name    string  `form:"name" binding:"required" json:"name"`
	Price   float64 `form:"price" binding:"required" json:"price"`
}

func AddWould(c *gin.Context) {
	var form WouldForm
	err := c.ShouldBind(&form)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"message": "参数获取失败"})
		return
	}
	would := dao.Would{
		GoodsId: form.GoodsId,
		Name:    form.Name,
		Price:   form.Price,
	}
	id := service.CheckGoodsById(form.GoodsId)
	if id {
		c.JSON(http.StatusInternalServerError, gin.H{"message": "提示这是您自己发布的手机"})
		return
	}

	err = global.DB.Create(&would).Error
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"message": "发布闲置失败"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"message": "发布闲置成功"})
}

type BuyForm struct {
	GoodsId int `form:"goodsId" binding:"required" json:"goodsId"`
}

func Buy(c *gin.Context) {
	var form BuyForm
	err := c.ShouldBind(&form)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"message": "参数获取失败"})
		return
	}
	// 开始事务
	tx := global.DB.Begin()

	// 事务操作结束时必须要记得调用 Rollback 或 Commit
	//defer 确保代码在函数结束时执行，即使是发生错误时也能执行。
	//recover() 用于捕获 panic，避免程序崩溃。
	//tx.Rollback() 用于回滚事务，确保数据的一致性。
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback() // 捕获 panic 并回滚事务
		}
	}()
	//查找商品
	var goods dao.Goods
	err = global.DB.Where("id = ?", form.GoodsId).First(&goods).Error
	if err != nil {
		tx.Rollback() //查找失败回滚
		c.JSON(http.StatusInternalServerError, gin.H{"message": "商品不存在"})
		return
	}
	// 商品已被购买，更新商品状态
	err = global.DB.Model(&goods).Update("status", "已售罄").Error //只更新status字段
	if err != nil {
		tx.Rollback() //状态修改失败回滚
		c.JSON(http.StatusInternalServerError, gin.H{"message": "状态修改失败"})
		return
	}
	err = tx.Commit().Error //提交事务
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"message": "事务提交失败"})
		return
	}
	// 返回成功响应
	c.JSON(http.StatusOK, gin.H{"message": "商品已被购买，状态已更新为已售罄"})
}
